﻿var votehtml = "vote/vote.html";
var voteplayerhtml = "vote/voteDetail.html";
var votesinguphtml = "vote/voteSignup.html";
var voteranking = "vote/voteRanking.html";
var votehistory = "vote/voteHistory.html"

var AccountGuid = "";
var VoteGUID = "";
var OpenId = "";
var contactsCallback_vote = myApp.onPageInit('vote', function (page) {

    //非微信浏览器下  不显示标题
    //    if (!ISS.utils.isWeiXin()) {
    //        mainView.hideNavbar();
    //        $$('.page-content').attr('style', 'margin-top:-44px')
    //    }

    // 过滤
    $$(".navbar-inner .right img").hide();
    // 返回
    $$("#vote_page").on("click", "a[data-action='back']", function () {
        var href = $$(this).attr("data-href");
        if (href && href != "") {
            window.location.href = href;
        }
    });
    //删除滚动后重新添加滚动
    var flag_InfiniteScroll = true;
    //是否需要滚动加载
    var flag_needScroll = true;
    //滚动事件只执行一次
    var flag_execute = false;

    LoadVoteInfo();

    //加载数据
    function LoadVoteInfo() {

        var _content = JSON.stringify(
            {
                AccountGuid: iss_localStorage.get("yuqing_appAccount"),
                OpenId: iss_localStorage.get("yuqing_appOpenId")
            }
        );
        if (iss_localStorage.get("yuqing_appAccount") == "" || iss_localStorage.get("yuqing_appAccount") == null || iss_localStorage.get("yuqing_appAccount") == "undefined") {
            myApp.alert('appAccount获取参数出错');
        } else if (iss_localStorage.get("yuqing_appOpenId") == "" || iss_localStorage.get("yuqing_appOpenId") == null || iss_localStorage.get("yuqing_appOpenId") == "undefined") {
            myApp.alert('appAccount获取参数出错');
        }

        $$('#lshg').on('click', function () {
            window.location.href = "voteHistory.html?Account=" + iss_localStorage.get("yuqing_appAccount");
        })
        $$.ajax({
            url: ISS_Constants.Url.const_wechatvote_info, //ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.FESTIVALS,
            data: { conditionParm: _content },
            crossDomain: true,
            dataType: "json",
            success: function (data, status) {
                if (data.datas) {
                    data.datas.VoteBeginTime = ISS.utils.dateToStr("yyyy-MM-dd", new Date(ISS.utils.ReplaceHMS(data.datas.VoteBeginTime)));
                    data.datas.VoteEndTime = ISS.utils.dateToStr("yyyy-MM-dd", new Date(ISS.utils.ReplaceHMS(data.datas.VoteEndTime)));
                    var searchTemplate = $$('#template-wechatvote-info').html();
                    if (searchTemplate) {
                        var compiledTemplate = Template7.compile(searchTemplate);
                        var html = compiledTemplate(data.datas);
                        $$("#voteinfo").append(html);
                        flag_InfiniteScroll = flag_needScroll = true;
                        //投票按钮事件加载
                        toupiao($$('.vote_btn'), data.datas.VoteGUID);
                        //选手图片选择事件
                        playerimg();
                        //底部按钮事件
                        menubottom(data.datas.IsSingUp, data.datas.AccountGuid, data.datas.VoteGUID, data.datas.VoteName)
                        //POPUP 弹出活动详情
                        $$('.open-about').on('click', function () {
                            myApp.popup('.popup-about');
                        });
                        //赋值全局变量
                        var AccountGuid = data.datas.AccountGuid;
                        var VoteGUID = data.datas.VoteGUID;
                        var OpenId = iss_localStorage.get("yuqing_appOpenId");
                    }
                }
            },
            error: function (xhr, status) { }
        });
    }
});
var contactsCallback_vote_detail = myApp.onPageInit('vote_detail', function (page) {
    // 过滤
    $$(".navbar-inner .right img").hide();
    //删除滚动后重新添加滚动
    var flag_InfiniteScroll = true;
    //是否需要滚动加载
    var flag_needScroll = true;
    //滚动事件只执行一次
    var flag_execute = false;
    //加载数据
    LoadVotedetail();
    //加载数据
    function LoadVotedetail() {
        var _content = JSON.stringify(
            {
                VoteGUID: ISS.utils.getParameter("VoteGUID"),
                CompetitionGUID: ISS.utils.getParameter("CompetitionGUID"),
                OpenId: iss_localStorage.get("yuqing_appOpenId")
            }
        );
        $$.ajax({
            url: ISS_Constants.Url.const_wechatvote_detail, //ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.FESTIVALS,
            data: { conditionParm: _content },
            crossDomain: true,
            dataType: "json",
            success: function (data, status) {
                if (data.datas) {
                    //                    data.datas.VoteBeginTime = ISS.utils.dateToStr("yyyy-MM-dd", new Date(ISS.utils.ReplaceHMS(data.datas.VoteBeginTime)));
                    //                    data.datas.VoteEndTime = ISS.utils.dateToStr("yyyy-MM-dd", new Date(ISS.utils.ReplaceHMS(data.datas.VoteEndTime)));
                    var searchTemplate = $$('#template-wechatvote-detail').html();
                    if (searchTemplate) {
                        var compiledTemplate = Template7.compile(searchTemplate);
                        var html = compiledTemplate(data.datas);
                        $$("#votedetail").html(html);
                        flag_InfiniteScroll = flag_needScroll = true;
                        //投票事件
                        toupiao($$('.votepage_btn'), data.datas.VoteGUID)
                        //跳转事件
                        rmainp()
                        //图片浏览事件
                        swiper()
                        //图片放大事件
                        photobrower(data.datas.ListImg);
                        var openid = iss_localStorage.get("yuqing_appOpenId")
                        var account = iss_localStorage.get("yuqing_appAccount")
                        var url = window.location.href
                        var image = "http://" + window.location.host + data.datas.ListImg[0].img;
                        var title = '投票活动';
                        var descript = '我是' + data.datas.CompetitionName + ',' + '亲!记得给我投票哦！'
                        //浏览记录(针对用户首次关注后所需要的数据)
                        recodedetail(openid, account, url, image, title, descript);
                        //分享事件
                        share(image, title, descript);
                    }
                }

            }, 
            error: function (xhr, status) { }
        });
    } 
    //分享按钮事件-弹出层
    $$("#vote_detail").on("click", ".share_btn", function () {
        myApp.popover(".popover-about", "body");
        $$(".popover-angle.on-left").attr("style", "display:none;");
        var pop = $$(".popover.popover-about")[0]
        pop.style.top = "2%";
        pop.style.left = "auto";
        pop.style.right = "1%";
    });
    //弹出完成事件
    $$(".popover").on("opened", function () {
        //
    });
});

var contactsCallback_voate_ranking = myApp.onPageInit('vote_ranking', function (page) {
    // 过滤
    $$(".navbar-inner .right img").hide();

    //删除滚动后重新添加滚动
    var flag_InfiniteScroll = true;
    //是否需要滚动加载
    var flag_needScroll = true;
    //滚动事件只执行一次
    var flag_execute = false;

    LoadVoteRanking();
    //加载数据
    function LoadVoteRanking() {
        var _content = JSON.stringify(
            {
                VoteGUID: ISS.utils.getParameter("VoteGUID"),
                AccountGuid: ISS.utils.getParameter("Account"),
                OpenId: iss_localStorage.get("yuqing_appOpenId")
            }
        );
        $$.ajax({
            url: ISS_Constants.Url.const_wechatvote_ranking, //ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.FESTIVALS,
            data: { conditionParm: _content },
            crossDomain: true,
            dataType: "json",
            success: function (data, status) {
                if (data.datas) {
                    $$('.head_line').html(unescape(ISS.utils.getParameter("title")))
                    for (var i = 0; i < data.datas.length; i++) {
                        data.datas[i].id = i + 1;
                    }
                    //                    data.datas.VoteBeginTime = ISS.utils.dateToStr("yyyy-MM-dd", new Date(ISS.utils.ReplaceHMS(data.datas.VoteBeginTime)));
                    //                    data.datas.VoteEndTime = ISS.utils.dateToStr("yyyy-MM-dd", new Date(ISS.utils.ReplaceHMS(data.datas.VoteEndTime)));
                    var searchTemplate = $$('#template-wechatvote-ranking').html();
                    if (searchTemplate) {
                        var compiledTemplate = Template7.compile(searchTemplate);
                        var html = compiledTemplate(data);
                        $$("#rows").html(html);
                        flag_InfiniteScroll = flag_needScroll = true;
                        rmainp()
                    }


                }

            },
            error: function (xhr, status) { }
        });
    }
});

var contactsCallback_vote_signup = myApp.onPageInit('vote_signup', function (page) {

    rmainp()

    $$("#playerimg").on("change", "input[type='file']", function () {
        var imgs = $$("#upload-container div");
        if (imgs.length >= 6) {
            myApp.alert("最多只能上传6张照片");
            return;
        }
        var that = $$(this);

        lrz(that[0].files[0], {
            width: 800
        })
        .then(function (rst) {
            var img = new Image();
            var div = document.createElement('div');
            div.className = 'col-33';

            $$(div).css("padding-bottom", "28%");
            $$(div).css(" background-size", "cover");
            $$(div).css("background-position", "center center");
            $$(div).css("margin", "15px 0 0 15px");
            $$(div).css("width", " -webkit-calc((100% - 15px*4)/ 3)");
            $$(div).css("width", "calc((100% - 15px*4)/ 3)");


            $$(div).css("background-image", "url(" + rst.base64 + ")");
            var _conditionParm = JSON.stringify({
                FileName: rst.origin.name,
                type: rst.origin.type,
                img: rst.base64
            });
            myApp.showPreloader();
            $$.ajax({
                url: ISS_Constants.Url.const_myshowscene_add_uploadloacl,
                data: { "conditionParm": _conditionParm },
                crossDomain: true,
                method: "POST",
                dataType: "jsonp",
                success: function (data, status) {
                    myApp.hidePreloader();
                    data = JSON.parse(data);
                    if (data && data.success) {
                        $$(div).attr("saveFileName", data.datas.saveFileName); //本地保存文件名
                        $$(div).attr("path", data.datas.path); //本地保存路径
                        $$('#upload-container').append(div);
                        return rst;
                    }
                },
                error: function (xhr, status) { myApp.hidePreloader(); }
            });

        });
    })
    $$("input[name='gender']").on('click', function () {
        $$("input[name='gender']").removeAttr("checked");
        $$(this).attr("checked", "checked");
    })
    //保存
    $$("#btn-save").click(function () {
        var imgs = $$("#upload-container div");
        if (imgs.length > 6) {
            myApp.alert("最多只能上传6张照片");
            return;
        }

        var competitionname = $$("#CompetitionName").val();
        var competitionsex = $$("input[name='gender'][checked]").val();
        var competitionphone = $$("#CompetitionPhone").val();
        var competitionintroduction = $$("#CompetitionIntroduction").val();



        if (competitionname == "") {
            myApp.alert("请输入内容！");
            return;
        } else if (competitionphone == "") {
            myApp.alert("请输入手机号！");
            return;
        } else if (CompetitionIntroduction == "") {
            myApp.alert("请输入简介！");
            return;
        }
        var ImgList = [];
        myApp.showPreloader();
        $$("#upload-container div").each(function () {
            var imgitem = {
                FileName: $$(this).attr("savefilename"),
                //                type: $$(this).attr("type"),
                //                img: $$(this).attr("data")
                saveFileName: $$(this).attr("saveFileName"),
                spath: $$(this).attr("path")
            };
            ImgList.push(imgitem);
        });
        var _conditionParm = JSON.stringify(
            {
                ListImg: ImgList,
                VoteGUID: ISS.utils.getParameter("VoteGUID"),
                CompetitionName: competitionname,
                //url: ISS_Constants.Url.const_myshowscene_add
                CompetitionSex: competitionsex,
                CompetitionPhone: competitionphone,
                CompetitionIDs: "",
                CompetitionAddress: "",
                OpenId: iss_localStorage.get("yuqing_appOpenId"),
                CompetitionIntroduction: competitionintroduction,
                CompetitionHobby: ""
            });
        $$.ajax({
            url: ISS_Constants.Url.const_wechatvote_signup,
            data: { "conditionParm": _conditionParm },
            crossDomain: true,
            method: "POST",
            dataType: "jsonp",
            success: function (data, status) {
                myApp.hidePreloader();
                data = JSON.parse(data);
                if (data) {
                    myApp.alert(data.msg);
                    myApp.closeModal(".popup-about");
                    return;
                } else {
                    myApp.alert(data.failMsg);
                }
            },
            error: function (xhr, status) { myApp.hidePreloader(); }
        });

    })

});

var contactsCallback_voate_history = myApp.onPageInit('vote_history', function (page) {
    // 过滤
    $$(".navbar-inner .right img").hide();

    //删除滚动后重新添加滚动
    var flag_InfiniteScroll = true;
    //是否需要滚动加载
    var flag_needScroll = true;
    //滚动事件只执行一次
    var flag_execute = false;
    rmainp()
    LoadVoteHistory();
    //加载数据
    function LoadVoteHistory() {
        var _content = JSON.stringify(
            {
                VoteGUID: ISS.utils.getParameter("VoteGUID"),
                AccountGuid: ISS.utils.getParameter("Account"),
                OpenId: iss_localStorage.get("yuqing_appOpenId")
            }
        );
        $$.ajax({
            url: ISS_Constants.Url.const_wechatvote_history, //ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.FESTIVALS,
            data: { conditionParm: _content },
            crossDomain: true,
            dataType: "json",
            success: function (data, status) {

                if (data.datas) {
                    for (var i = 0; i < data.datas.length; i++) {
                        data.datas[i].id = i + 1;
                        data.datas[i].VoteBeginTime = ISS.utils.dateToStr("yyyy-MM-dd", new Date(ISS.utils.ReplaceHMS(data.datas[i].VoteBeginTime)));
                        data.datas[i].VoteEndTime = ISS.utils.dateToStr("yyyy-MM-dd", new Date(ISS.utils.ReplaceHMS(data.datas[i].VoteEndTime)));
                    }
                    var searchTemplate = $$('#template-wechatvote-history').html();
                    if (searchTemplate) {
                        var compiledTemplate = Template7.compile(searchTemplate);
                        var html = compiledTemplate(data);
                        $$(".rank_list").html(html);
                        flag_InfiniteScroll = flag_needScroll = true;
                        rmainp()
                    }
                    $$('#rows tr').on('click', function () {
                        debugger
                        var guid = $$(this).attr('guid');
                        window.location.href = "voteRanking.html?voteguid=" + guid + "&Account=" + iss_localStorage.get("yuqing_appAccount") + "&title=" + escape($$(this).find('td p').html().trim());
                    })

                }

            },
            error: function (xhr, status) { }
        });
    }
});

function toupiao(obj, voteguid) {
    obj.on('click', function () {
        var obj = new Object();
        obj.VoteGUID = voteguid;
        obj.OpenId = iss_localStorage.get("yuqing_appOpenId");
        var curr = $$(this).parent().find('.count_number p');
        var voted = curr.html();
        obj.CompetitionGUID = ISS.utils.getParameter("CompetitionGUID") ? ISS.utils.getParameter("CompetitionGUID") : $$(this).parent().find('.tickes_number').attr('id');
        var _content = JSON.stringify(obj);
        $$.ajax({
            url: ISS_Constants.Url.const_wechatvote_voted, //ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.FESTIVALS,
            data: { conditionParm: _content },
            crossDomain: true,
            dataType: "json",
            success: function (data, status) {
                if (data.datas) {
                    curr.html(parseInt(voted) + 1);
                    myApp.alert(data.msg);
                } else {
                    myApp.alert(data.msg);
                }
            },
            error: function (xhr, status) { }
        })
    })
}

function playerimg() {
    $$('.vote-item .vote-img').on('click', function () {
        var h = $$(this).attr('href');
        window.location.href = h;
    })
}

function menubottom(issignup, account, voteguid, votename) {
    $$('.top_menu li a').on('click', function () {

        if ($$(this).attr('id') == "pm") {
            window.location.href = "voteRanking.html?voteguid=" + voteguid + "&Account=" + account + "&title=" + escape(votename);
        } else if ($$(this).attr('id') == "bm") {
            if (issignup == "1") {
                myApp.alert('您已经报名了!');
            } else {
                window.location.href = "voteSignup.html?voteguid=" + voteguid + "&Account=" + account;
            }
        }
    })
}

function rmainp() {
    $$('.navbar-inner .left a').on('click', function () {
        window.location.href = "vote.html?voteguid=" + ISS.utils.getParameter("VoteGUID") + "&Account=" + ISS.utils.getParameter("Account");
    })
}

function swiper() {
    var mySwiper = myApp.swiper('.swiper-container', {
        pagination: '.swiper-pagination'
    });
}

function photobrower(imglist) {
    var obj = new Array();
    for (var i = 0; i < imglist.length; i++) {
        obj.push(imglist[i].img);
    }

    var myPhotoBrowserPopup = myApp.photoBrowser({
        photos: obj,
        theme: 'dark',
        type: 'popup'
    });
    $$('.swiper-container').on('click', function () {
        myPhotoBrowserPopup.open();
    });

}

function initData() {
    var href = window.location.href;
    if (href.indexOf(votehtml) > -1) {
        contactsCallback_vote.trigger();
    } else if (href.indexOf(voteplayerhtml) > -1) {
        contactsCallback_vote_detail.trigger();
    } else if (href.indexOf(votesinguphtml) > -1) {
        contactsCallback_vote_signup.trigger();
    } else if (href.indexOf(voteranking) > -1) {
        contactsCallback_voate_ranking.trigger();
    } else if (href.indexOf(votehistory) > -1) {
        contactsCallback_voate_history.trigger();
    }
}

function recodedetail(openId, accountGuid, url, imageurl, title, describe) {
    if (openId != null && accountGuid != null) {
        RecodeLog(openId, accountGuid, url, imageurl, title, describe);
    }
}
initData();